import java.io.IOException;
import java.net.*;
import java.util.Scanner;

public class UdpEchoClient {

    public DatagramSocket socket=null;
    //Udp本身不连接，就自己创建变量保存

    public String severIp;
    public int severPort;

    public UdpEchoClient(String severIp,int severPort) throws SocketException {
        this.severIp=severIp;
        this.severPort=severPort;
        socket=new DatagramSocket();
    }

    public void start() throws IOException {
        Scanner scanner=new Scanner(System.in);
        while(true){
            System.out.println("请输入要发送的内容");
            if(!scanner.hasNext())
                break;
            String request=scanner.next();
            DatagramPacket requestPacket=new DatagramPacket(request.getBytes(),request.getBytes().length, InetAddress.getByName(severIp),severPort);
            socket.send(requestPacket);

            DatagramPacket responsePacket=new DatagramPacket(new byte[4096],4096);
            socket.receive(responsePacket);

            String response=new String(responsePacket.getData(),0, responsePacket.getLength());
            System.out.println(response);
        }
    }

    public static void main(String[] args) throws IOException {
        UdpEchoClient client=new UdpEchoClient("127.0.0.1",9090);
        client.start();
    }
}
